<template>
  <div class="login-container">

    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">{{ $t('login.title') }}</h3>
        <svg-icon :icon-class="onlineIcon" class="online-status" />
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :type="passwordType"
          v-model="loginForm.password"
          :placeholder="$t('login.password')"
          name="password"
          auto-complete="on"
          @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye" />
        </span>
      </el-form-item>

      <el-form-item prop="server">
        <span class="svg-container">
          <svg-icon icon-class="server" />
        </span>
        <el-input
          v-model="loginForm.server"
          placeholder="请输入服务器地址"
          name="server"
          type="text"
          auto-complete="on"
        />
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">{{ online?"登陆(在线)":"登陆(离线)" }}</el-button>

    </el-form>

  </div>
</template>

<script>
import { isvalidUsername, validateURL, validateIP } from '@/utils/validate'
import { getUsername, getPassword, getServer, getInternalServer } from '@/utils/auth'
import { constantRouterMap } from '@/router'
import { getWorklist } from '@/utils/storage'
import { isOnline } from '@/utils/commonutils'

/**
 * Login的逻辑：
 * 1. 打开登录界面时检测Cookie中是否于用户名密码信息，如果有自动填充进去，如果没有则留空，只保存最近一次的用户信息
 * 2. 登录成功后把用户名密码放入Cookie中，同时存到store中，同时把获取的token存放到store中和Cookie中
 * 3. 每次发request时，先使用store中的token获取，如果失败的话，隐含登录一下获取token，再更新store中的token
 */
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    const validateServer = (rule, value, callback) => {
      const servers = value.split(';')
      if (servers.length === 1) {
        if (!validateURL(value)) {
          callback(new Error('请输入正确的服务器地址, 格式为：http://<server>:<port>'))
        } else {
          callback()
        }
      } else if (servers.length === 2) {
        if (!validateURL(servers[0])) {
          callback(new Error('请输入正确的服务器地址'))
        } if (!validateIP(servers[1])) {
          callback(new Error('请输入正确的内部服务器地址，格式为：<server>:<port>'))
        } else {
          callback()
        }
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        server: 'http://'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        server: [{ required: true, trigger: 'blue', validator: validateServer }]
      },
      passwordType: 'password',
      loading: false,
      showDialog: false,
      redirect: undefined,
      onlineIcon: isOnline() ? 'online' : 'offline'
    }
  },
  computed: {
    online() {
      console.log('this.$store.state.app.online: ' + this.$store.state.app.online)
      return this.$store.state.app.online
    },
    alreadyLogin() {
      if (this.$store.state.user.token) {
        console.log('已登陆, token: ' + this.$store.state.user.token)
        return true
      } else {
        console.log('未登陆')
        return false
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted: function() {
    this.loginForm.username = getUsername() || ''
    this.loginForm.password = getPassword() || ''
    this.loginForm.server = this.getCompletServer() || 'http://'
    document.addEventListener('online', this.updateOnlineStatus, false)
    document.addEventListener('offline', this.updateOfflineStatus, false)
    console.log('当前在线状态：' + this.online)
  },
  methods: {
    updateOnlineStatus(e) {
      this.$store.dispatch('setOnlineStatus', true)
      this.onlineIcon = 'online'
      if (this.alreadyLogin) {
        console.log('==>已登陆！')
        this.$store.dispatch('LoginByUsername', this.loginForm)
      } else {
        console.log('==>未登陆！')
      }
    },
    updateOfflineStatus(e) {
      this.$store.dispatch('setOnlineStatus', false)
      this.onlineIcon = 'offline'
      if (this.alreadyLogin) {
        console.log('==>已登陆！')
        this.$store.dispatch('OfflineLoginByUsername', this.loginForm)
      } else {
        console.log('==>未登陆！')
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    getCompletServer() {
      const server = getServer()
      const internalServer = getInternalServer()
      if (!server) {
        return null
      } else if (!internalServer) {
        return server
      } else {
        const _internalServer = server.substring(server.indexOf('://') + 3).split(':')[0]
        if (internalServer === _internalServer) {
          return server
        } else {
          return server + ';' + internalServer
        }
      }
    },
    handleLogin() {
      const that = this
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (that.online) {
            that.onlineLogin()
          } else {
            that.offlineLogin()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onlineLogin() {
      this.loading = true
      this.$store.dispatch('LoginByUsername', this.loginForm).then(
        () => getWorklist()
      ).then(
        worklist => {
          const newRoutes = []
          for (var i = 0; i < worklist.length; i++) {
            const newRoute = {
              path: worklist[i].workcard.workuid,
              component: () => import('@/views/workcard/workcard'),
              props: { workuid: worklist[i].workcard.workuid },
              name: worklist[i].workcard.workuid,
              meta: { title: worklist[i].workcard.workrelattrs.find(v => v.name === 'ID').value, noCache: 'true' }
            }
            newRoutes.push(newRoute)
          }
          const route = constantRouterMap.find(r => r.name === 'workcards')
          route.children = route.children.concat(newRoutes).filter((obj, index, self) =>
            index === self.findIndex((t) => (t.name === obj.name)))
          this.$router.addRoutes([route])
        }
      ).then(() => {
        this.loading = false
        this.$router.push({ path: this.redirect || '/' })
      }).catch((error) => {
        this.loading = false
        if (error.message === 'Network Error') {
          this.$message({
            message: '网络错误，未连接到服务器！',
            type: 'error'
          })
        } else if (error.response && error.response.data && error.response.data.message) {
          this.$message({
            message: error.response.data.message,
            type: 'error'
          })
        } else if (error.message) {
          this.$message({
            message: error.message,
            type: 'error'
          })
        } else {
          this.$message({
            message: '登陆错误！',
            type: 'error'
          })
        }
      })
    },
    offlineLogin() {
      this.loading = true
      this.$store.dispatch('OfflineLoginByUsername', this.loginForm).then(
        () => getWorklist()
      ).then(
        worklist => {
          const newRoutes = []
          for (var i = 0; i < worklist.length; i++) {
            const newRoute = {
              path: worklist[i].workcard.workuid,
              component: () => import('@/views/workcard/workcard'),
              props: { workuid: worklist[i].workcard.workuid },
              name: worklist[i].workcard.workuid,
              meta: { title: worklist[i].workcard.workrelattrs.find(v => v.name === 'ID').value, noCache: 'true' }
            }
            newRoutes.push(newRoute)
          }
          const route = constantRouterMap.find(r => r.name === 'workcards')
          route.children = route.children.concat(newRoutes).filter((obj, index, self) =>
            index === self.findIndex((t) => (t.name === obj.name)))
          this.$router.addRoutes([route])
        }
      ).then(() => {
        this.loading = false
        this.$router.push({ path: this.redirect || '/' })
      }).catch(error => {
        this.loading = false
        this.$message({
          message: error.message,
          type: 'error'
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

  $bg:#283443;
  $light_gray:#eee;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input{
      color: $cursor;
      &::first-line {
        color: $light_gray;
      }
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;
      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;
        &:-webkit-autofill {
          -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }
    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 520px;
    max-width: 100%;
    padding: 35px 35px 15px 35px;
    margin: 120px auto;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
    .online-status {
      // color: #fff;
      position: absolute;
      top: 5px;
      right: 60px;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
}
</style>
